[LeetCode] 515 - Find Largest Value in Each Tree Row

題意

找出樹中每一層最大的元素。

解法

BFS。

程式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var largestValues = function(root) {
if ( !root ) return [];
let queue = [root];
let result = [];
while( queue.length !== 0 ){
let length = queue.length;
let max = queue[0].val;
for ( let i = 0; i < length; i ++ ){
let node = queue.shift();
if ( node.val > max ) max = node.val;
if ( node.left ) queue.push(node.left);
if ( node.right ) queue.push(node.right);
}
result.push(max);
}
return result;
};